//
//  StockInquryDetailVC.m
//  ProjectforHDX
//
//  Created by motom on 2016/11/21.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "StockInquryDetailVC.h"

#import "StockInquiryDetailCell.h"

@interface StockInquryDetailVC ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,weak)UIView *topView;

@property (nonatomic, strong) NSMutableArray *plates;

@property (nonatomic, assign) NSInteger page;

@end

@implementation StockInquryDetailVC
{
    UINib *nib;
}


- (NSMutableArray *)plates
{
    if (!_plates) {
        _plates = [NSMutableArray array];
    }
    return _plates;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    self.page = (long)1;
    [self setupView];
    [self requestData:self.page];
    // Do any additional setup after loading the view.
}

#pragma mark 初始化界面

- (void)setupData
{
    [self requestData:self.page];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc]initWithImage:BDFILEIMAGENAEM(@"default/back_gray") style:UIBarButtonItemStylePlain target:self action:@selector(backView)];
    self.navigationItem.leftBarButtonItem = barButtonItem;
    
}

- (void)setupView
{
    
    self.view.backgroundColor = [UtilCheck hexStringToColor:@"f1f6f8" alpha:1.0];
    
   
    UIView *topView = [self createTopView];
    [self.view addSubview:topView];
    
    UITableView *tableView = [[UITableView alloc]init];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.delegate = self;
    tableView.dataSource = self;
    
    NSLog(@"%f",[UIScreen mainScreen].bounds.size.height - topView.height - 20);
    self.tableView = tableView;
    [tableView setFrame:CGRectMake(0, CGRectGetMaxY(_topView.frame)+10, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - CGRectGetMaxY(_topView.frame) - 75)];
    
    [self.view addSubview:tableView];
    
    __weak typeof(self) weakSelf = self;
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        if (self.plates.count %20 != 0) {//如果最后一页没满20条，则不加载
            [self.tableView.footer endRefreshing];
            [Toolobject showTextWithMessage:@"暂无更多数据"];
            return;
        }
        
        // 进入刷新状态后会自动调用这个block
        
        NSInteger page=weakSelf.page+1;//当前的页码加1
        weakSelf.page ++;
        [self requestData:page];
        
        [self.tableView.footer endRefreshing];
            
    }];
                             //加载全部完毕
            
//            [self.tableView.footer noticeNoMoreData];
        
        
        

}

- (void)backView
{
    AppDelegate * app = [UIApplication sharedApplication].delegate;
    app.shouldChangeOrientation = YES;
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (UIView *)createTopView
{
    CGFloat labelFont = 14.f;
    
    UIView *topView = [[UIView alloc]init];
    _topView = topView;
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    

    
    UILabel *count = [[UILabel alloc]init];
    count.text = [UtilCheck language:@"seeting.number"];
    count.textAlignment = NSTextAlignmentCenter;
    count.font = [UIFont systemFontOfSize:labelFont];
    [topView addSubview:count];
    
    
    UILabel *plateCount = [[UILabel alloc]init];
    plateCount.textColor = [UtilCheck hexStringToColor:@"1949a4" alpha:1.0];
    plateCount.text = self.plate.number;
    plateCount.font = [UIFont systemFontOfSize:labelFont];
    plateCount.textAlignment = NSTextAlignmentCenter;
    [topView addSubview:plateCount];
    
    UILabel *name = [[UILabel alloc]init];
    name.text = [UtilCheck language:@"show.panelName"];
    name.numberOfLines = 0;
    name.font = [UIFont systemFontOfSize:13.f];
    name.textAlignment = NSTextAlignmentCenter;
    [topView addSubview:name];
    
    UILabel *plateName = [[UILabel alloc]init];
    plateName.numberOfLines = 0;
    plateName.textColor = [UtilCheck hexStringToColor:@"1949a4" alpha:1.0];
    plateName.textAlignment = NSTextAlignmentCenter;
    plateName.font = [UIFont systemFontOfSize:labelFont];
    plateName.text = self.plate.name;
   
    CGRect frame = [plateName.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width/4, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]} context:nil];
    [plateName setFrame:frame];
    [topView addSubview:plateName];
    
    UILabel *code = [[UILabel alloc]init];
    code.font = [UIFont systemFontOfSize:labelFont];
    code.text = [UtilCheck language:@"order.part.code"];
    [code sizeToFit];
    code.textAlignment = NSTextAlignmentCenter;
    [topView addSubview:code];
    
    UILabel *plateCode = [[UILabel alloc]init];
    plateCode.text = self.plate.code;
    plateCode.font = [UIFont systemFontOfSize:labelFont];
    plateCode.numberOfLines = 0;
    plateCount.textAlignment = NSTextAlignmentCenter;
    plateCode.textColor = [UtilCheck hexStringToColor:@"1949a4" alpha:1.0];
    CGRect frame2 = [plateCode.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width/4, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20]} context:nil];
    [plateCode setFrame:frame2];
    [topView addSubview:plateCode];
    
    CGFloat maxHeight;
    if (plateName.height > plateCode.height) {
        maxHeight = plateName.height;
    }
    else
    {
        maxHeight = plateCode.height;
    }
    
    //设置大小
    [topView setFrame:CGRectMake(0, 10, [UIScreen mainScreen].bounds.size.width, maxHeight)];

    CGFloat width = topView.bounds.size.width / 5;
    
    [count setFrame:CGRectMake(0, 0, 40, topView.height)];
    
//    [plateCount setFrame:CGRectMake(count.left, 0, 0, 0)];
    [plateCount sizeToFit];

    
    [name setFrame:CGRectMake(0, 0, width, topView.height)];
    
    [plateName setFrame:CGRectMake(0, 0, width-10, topView.height)];
    
    [code setFrame:CGRectMake(0, 0, width-10, topView.height)];
    
    [plateCode setFrame:CGRectMake(0, 0, width+20, topView.height)];
    
   
    
    //位置
    CGFloat top = 0;
    
    count.left = 0;
    count.top = top;
    
    plateCount.left = count.right;
    plateCount.top = topView.height/2 -8;
    
    name.left = plateCount.right;
    name.top = top;
    
    plateName.left = name.right;
    plateName.top = top;
    
    code.left = plateName.right;
    code.top = top;
    
    plateCode.left = code.right;
    plateCode.top = top;
    
    return topView;
}



#pragma mark 网络请求
//{
//    "code":"C1193.101"				//带版本的板件号
//    "key":"AABBCCDDEEFFGG"			//用户凭证
//    "page":1			//页码
//    "size":20		//每页条数
//    
//}

- (void)requestData:(NSInteger)page
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    params[@"code"] = self.plate.code;
    params[@"warehouse"]= self.plate.warehouse;
    params[@"page"] = [NSString stringWithFormat:@"%ld",(long)page];
    params[@"size"] = @"20";

    [[BDHUD sharedManager] showBDHUD:self.view title:nil];

    [AFHttpTool postJsonDatawithUrl:@"/inventoryDetails" parameters:params success:^(id responseObject) {
        NSLog(@"%@",responseObject);
        NSArray *arr = responseObject[@"data"];
        if (self.page != 1) {
            [self.plates addObjectsFromArray:(NSMutableArray *)[self modelWithDic:arr]];
        }
        else{
        self.plates = (NSMutableArray *)[self modelWithDic:arr];
        }
        [self.tableView reloadData];
        [[BDHUD sharedManager] dismissHUD];

    } fail:^(id responseObject, NSError *error) {
        [[BDHUD sharedManager] dismissHUD];
        NSLog(@"%@",responseObject);
    }];


}

#pragma mark tableview的delegate和datasource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 91;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.plates.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identy = @"StockInquiryDetailCell";
    if (!nib) {
        nib = [UINib nibWithNibName:@"StockInquiryDetailCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identy];
    }
    StockInquiryDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:identy];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setmodel:self.plates[indexPath.row]];
    if ((long)indexPath.row+1 > 99) {
        cell.numberBtn.width = 30;
    }
    else
    {
        cell.numberBtn.width = 20;
    }
    [cell.numberBtn setTitle:[NSString stringWithFormat:@"%ld",(long)indexPath.row+1] forState:UIControlStateNormal];
    
    return cell;
}

- (NSArray *)modelWithDic:(NSArray *)arr
{
    NSMutableArray *muArr = [NSMutableArray array];
    for (int i = 0 ; i < arr.count; i ++) {
        NSMutableDictionary *dic = arr[i];
        dic[@"number"] = [NSString stringWithFormat:@"%@",dic[@"number"]];
        PlateModel *plate = [[PlateModel alloc]init];
        [plate setValuesForKeysWithDictionary:dic];
        [muArr addObject:plate];
    }
    return muArr;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (BOOL)shouldAutorotate
{
    
    return NO;
    
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    
    return UIInterfaceOrientationMaskLandscape;
    
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    
    return UIInterfaceOrientationLandscapeLeft;
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
